package com.wawayaya.api;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.Date;

import com.creative.accountsdk.UserData;
import com.wawayaya.AppContext;
import com.wawayaya.api.interf.ApiResponseJsonListener;
import com.wawayaya.api.interf.ApiResponseListener;
import com.wawayaya.api.remote.ApiConstans;
import com.wawayaya.bean.User;
import com.wawayaya.cache.UserDataCache;
import com.wawayaya.util.TDevice;
import com.wawayaya.util.TimeZoneUtil;
/**
 *
 * 统一网络请求
 */
@SuppressLint("NewApi")
public class ApiRequestHelper {

    private static final String TAG  = "RequestManager";
    public static RequestQueue mRequestQueue = Volley.newRequestQueue(AppContext.getInstance());

    /**
     * 不为空的本地时间 进行验证是否在5分钟之内
     * @param timestamp
     */
    private  static void  calculateTime(String timestamp){
        long currentTime = new Date().getTime();
        long  almost= currentTime-new Long(timestamp);
        long  fiveSecond =5*60*1000;
        if(almost<fiveSecond){
            return ;
        }
    }

    /**
     * get 返回String
     *
     * @param url
     *            连接
     * @param context
     *            上下文
     * @param listener
     *            回调
     */
    public static void get(String url, final Context context,ApiRequestParams params,Integer requestType, final ApiResponseJsonListener listener) {
        String  bf = pingUrl(url, params, context);
        Log.e(TAG, "request get URL:" + bf.toString());
        ApiRequestByteArray request = new ApiRequestByteArray(Request.Method.GET,bf.toString(), null,
                responseListenerT(context,listener, requestType),
                responseErrorT(listener,requestType));
        addRequest(request, context);
    }

    /**
     * 拼接url
     * @param url
     * @param params
     * @param context
     * @return
     */
    public  static  String  pingUrl(String url,ApiRequestParams params,Context context){
        params = commonParams(0,params,context);
        StringBuffer bf = new StringBuffer(url);
        bf.append("?");
        if(null!=params){
            for(int i=0;i<params.getParamsList().size();i++){
                BasicNameValuePair  nameValuePair= params.getParamsList().get(i);
                bf.append(nameValuePair.getName());
                bf.append("=");
                bf.append(nameValuePair.getValue());
                if(i!=params.getParamsList().size()-1){
                    bf.append("&");
                }
            }
        }
        return bf.toString();
    }

    /**
     * post 返回String
     *
     * @param url
     *            接口
     * @param context
     *            上下文
     * @param params
     *            post需要传的参数
     * @param listener
     *            回调
     */
    public static void post(String url,final Context context, ApiRequestParams params,final String uid,final ApiResponseListener listener) {
        Log.e(TAG,"url.......:"+url);
        params = commonParams(0,params,context);
        ApiRequestByteArray request = new ApiRequestByteArray(Request.Method.POST,
                url, params, responseListener(listener),responseError(listener));
        addRequest(request, context);
    }


    /**
     * post 返回对象
     *
     * @param url
     *            接口
     * @param context
     *            上下文
     * @param params
     *            post需要传的参数
     * @param listener
     *            回调
     */
    public static <T> void post(String url, final Context context,
                                ApiRequestParams params,final Integer requestType,
                                final ApiResponseJsonListener listener) {
        Log.e(TAG,"url.......:"+url);
        params = commonParams(requestType,params,context);
        ApiRequestByteArray request = new ApiRequestByteArray(Request.Method.POST,
                url, params,
                responseListenerT(context, listener, requestType),
                responseErrorT(listener, requestType));
        addRequest(request, context);
    }

    /**
     * get 返回String
     *
     * @param url
     *            连接
     * @param context
     *            上下文
     * @param listener
     *            回调
     */
    public static void getHandler(String url, final Context context,ApiRequestParams params,Integer requestType, final ApiResponseJsonListener listener) {
        String  bf = pingUrl(url, params, context);
        Log.e(TAG, "request get URL:" + bf.toString());
        ApiRequestByteArray request = new ApiRequestByteArray(Request.Method.GET,bf.toString(), null,
                responseListenerHandler(context, listener, requestType),
                responseErrorT(listener,requestType));
        addRequest(request, context);
    }

    /**
     *  家长中心、教师中心  post 返回对象
     *
     * @param url
     *            接口
     * @param context
     *            上下文
     * @param params
     *            post需要传的参数
     * @param listener
     *            回调
     */
    public static <T> void postTeacherHandler(String url, final Context context,
                                       ApiRequestParams params,final Integer requestType,
                                       final ApiResponseJsonListener listener) {
        Log.e(TAG,"url.......:"+url);
        params = commonParams(requestType,params,context);
        ApiRequestByteArray request = new ApiRequestByteArray(Request.Method.POST,
                url, params,
                responseTeacherListenerHandler(context, listener, requestType),
                responseErrorT(listener, requestType));
        addRequest(request, context);
    }


    /**
     *  家长中心、教师中心  get 返回对象
     *
     * @param url
     *            连接
     * @param context
     *            上下文
     * @param listener
     *            回调
     */

    public static void getTeacherHandler(String url, final Context context,ApiRequestParams params,Integer requestType, final ApiResponseJsonListener listener) {
        String  bf = pingUrl(url, params, context);
        Log.e(TAG, "request get URL:" + bf.toString());
        ApiRequestByteArray request = new ApiRequestByteArray(Request.Method.GET,bf.toString(), null,
                responseTeacherListenerHandler(context, listener, requestType),
                responseErrorT(listener,requestType));
        addRequest(request, context);
    }


    /**
     * post 返回对象
     *
     * @param url
     *            接口
     * @param context
     *            上下文
     * @param params
     *            post需要传的参数
     * @param listener
     *            回调
     */
    public static <T> void postHandler(String url, final Context context,
                                ApiRequestParams params,final Integer requestType,
                                final ApiResponseJsonListener listener) {
        Log.e(TAG,"url.......:"+url);
        params = commonParams(requestType,params,context);
        ApiRequestByteArray request = new ApiRequestByteArray(Request.Method.POST,
                url, params,
                responseListenerHandler(context, listener, requestType),
                responseErrorT(listener, requestType));
        addRequest(request, context);
    }

    /**
     * 成功消息监听 返回对象
     *
     * @param l
     * @return
     */
    protected static <T> Response.Listener<byte[]> responseListenerHandler(final Context context,final ApiResponseJsonListener l,
                                                                     final Integer requestType) {
        return new Response.Listener<byte[]>() {
            @Override
            public void onResponse(byte[] arg0) {
                String data = null;
                JSONObject  jsonObject = null;
                try {
                    data = new String(arg0, "UTF-8");
                    if(requestType!= ApiConstans.PAY_PAGE){
                        Log.e(TAG,"return string:"+data);
                        jsonObject = new JSONObject(data);
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                ApiResponseData apiResponseData = new ApiResponseData();
                apiResponseData.setRquestType(requestType);

                if(jsonObject.optInt("flag")== ApiConstans.FLAG_TOKEN_ERROR){
                    if(!tokenDialogShow && requestType!= ApiConstans.MYBOOKSHELF_MERGEMINE){
                       // tokenDialog(context);
                        tokenDialogShow = true;
                    }
                    apiResponseData.setMessage(jsonObject.optString(ApiConstans.MESSAGE));
                    apiResponseData.setFlag(jsonObject.optInt(ApiConstans.FLAG));
                    l.success0(apiResponseData);
                    return ;
                }
                if(requestType== ApiConstans.DUba_VERSION_CHECK){
                    JSONObject  jo=  jsonObject.optJSONObject("retMap");
                    apiResponseData.setRetinfo(jo);
                    l.success1(apiResponseData);
                    return ;
                }

                if(requestType!= ApiConstans.PAY_PAGE) {
                    apiResponseData.setFlag(jsonObject.optInt(ApiConstans.FLAG));
                    apiResponseData.setMessage(jsonObject.optString(ApiConstans.MESSAGE));

                    if (jsonObject.optInt(ApiConstans.FLAG) == ApiConstans.FLAG_SUCCESS) {
                        JSONObject retInfo = jsonObject.optJSONObject(ApiConstans.RETINFO);
                        apiResponseData.setUid(retInfo.optInt(ApiConstans.REQUEST_UID));
                        apiResponseData.setRetinfo(retInfo);
                        apiResponseData.setServerTimestamp(retInfo.optString(ApiConstans.RETINFO_SERVERTIME));

                        if (requestType == ApiConstans.USER_LOGIN) {
                            apiResponseData = setData(apiResponseData, retInfo);

                        } else if (requestType != ApiConstans.USER_REGISTER) {
                            apiResponseData = setData(apiResponseData, retInfo);
                        }

                        l.success1(apiResponseData);
                    }
                    if (jsonObject.optInt(ApiConstans.FLAG) == ApiConstans.FLAG_ERROR) {

                        if (requestType == ApiConstans.WORD) {
                            apiResponseData.setRetinfo(jsonObject);
                            l.success1(apiResponseData);
                        } else {
                            Log.e(TAG,"返回的时间 。。。。。。。。。。"+jsonObject.optString(ApiConstans.MESSAGE));
                            if(jsonObject.optString(ApiConstans.MESSAGE).contains("时间") || jsonObject.optString(ApiConstans.MESSAGE).contains("Time")){
                              //  timeDialog(context, jsonObject.optString(ApiConstans.MESSAGE));
                                if(!timeDialogShow){
                                //timeDialog.show();
                                    timeDialogShow = true;
                                }
                            }
                            l.success0(apiResponseData);
                        }
                    }
                }else{
                    if(null!=data){
                        //支付html源码信息
                        apiResponseData.setMessage(data);
                        l.success1(apiResponseData);
                    }else{
                        l.success0(apiResponseData);
                    }
                }
            }
        };
    }

    /**
     *  teacher Parent 成功消息监听 返回对象
     *
     * @param l
     * @return
     */
    protected static <T> Response.Listener<byte[]> responseTeacherListenerHandler(final Context context,final ApiResponseJsonListener l,
                                                                           final Integer requestType) {
        return new Response.Listener<byte[]>() {
            @Override
            public void onResponse(byte[] arg0) {
                String data = null;
                JSONObject  jsonObject = null;
                try {
                    data = new String(arg0, "UTF-8");
                    Log.e(TAG,"return string:"+data);
                    jsonObject = new JSONObject(data);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                ApiResponseData apiResponseData = new ApiResponseData();
                apiResponseData.setRquestType(requestType);
                JSONObject  jo=  jsonObject.optJSONObject("retinfo");
                apiResponseData.setRetinfo(jo);
                l.success1(apiResponseData);
            }
        };
    }

    private static  boolean tokenDialogShow = false;
    private static  boolean timeDialogShow = false;
    /**
     * 成功消息监听 返回对象
     *
     * @param l
     * @return
     */
    protected static <T> Response.Listener<byte[]> responseListenerT(final Context context,final ApiResponseJsonListener l,
                                                                     final Integer requestType) {
        return new Response.Listener<byte[]>() {
            @Override
            public void onResponse(byte[] arg0) {
                String data = null;
                JSONObject  jsonObject = null;
                try {
                    data = new String(arg0, "UTF-8");
                    if(requestType!= ApiConstans.PAY_PAGE){
                        Log.e(TAG,"return string:"+data);
                        jsonObject = new JSONObject(data);
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                ApiResponseData apiResponseData = new ApiResponseData();
                apiResponseData.setRquestType(requestType);

                if(jsonObject.optInt("flag")== ApiConstans.FLAG_TOKEN_ERROR){
                    if(!tokenDialogShow && requestType!= ApiConstans.MYBOOKSHELF_MERGEMINE){
                        //tokenDialog(context);
                        tokenDialogShow = true;
                    }
                    apiResponseData.setMessage(jsonObject.optString(ApiConstans.MESSAGE));
                    apiResponseData.setFlag(jsonObject.optInt(ApiConstans.FLAG));
                    l.success0(apiResponseData);
                    return ;
                }
                if(requestType== ApiConstans.DUba_VERSION_CHECK){
                    JSONObject  jo=  jsonObject.optJSONObject("retMap");
                    apiResponseData.setRetinfo(jo);
                    l.success1(apiResponseData);
                    return ;
                }

                if(requestType!= ApiConstans.PAY_PAGE) {
                    apiResponseData.setFlag(jsonObject.optInt(ApiConstans.FLAG));
                    apiResponseData.setMessage(jsonObject.optString(ApiConstans.MESSAGE));

                    if (jsonObject.optInt(ApiConstans.FLAG) == ApiConstans.FLAG_SUCCESS) {
                        JSONObject retInfo = jsonObject.optJSONObject(ApiConstans.RETINFO);
                        apiResponseData.setUid(retInfo.optInt(ApiConstans.REQUEST_UID));
                        apiResponseData.setRetinfo(retInfo);
                        apiResponseData.setServerTimestamp(retInfo.optString(ApiConstans.RETINFO_SERVERTIME));

                        if (requestType == ApiConstans.USER_LOGIN) {
                            apiResponseData = setData(apiResponseData, retInfo);

                        } else if (requestType != ApiConstans.USER_REGISTER) {
                            apiResponseData = setData(apiResponseData, retInfo);
                        }
                     /*   DBThread  saveDBThread = new DBThread(apiResponseData);
                        saveDBThread.run();*/

                        l.success1(apiResponseData);
                    }
                    if (jsonObject.optInt(ApiConstans.FLAG) == ApiConstans.FLAG_ERROR) {

                        if (requestType == ApiConstans.WORD) {
                            apiResponseData.setRetinfo(jsonObject);
                            l.success1(apiResponseData);
                        } else {
                            Log.e(TAG,"返回的时间 。。。。。。。。。。"+jsonObject.optString(ApiConstans.MESSAGE));
                            if(jsonObject.optString(ApiConstans.MESSAGE).contains("时间") || jsonObject.optString(ApiConstans.MESSAGE).contains("Time")){
                                //timeDialog(context, jsonObject.optString(ApiConstans.MESSAGE));
                                if(!timeDialogShow){
                                  //  timeDialog.show();
                                    timeDialogShow = true;
                                }
                            }
                            l.success0(apiResponseData);
                        }
                    }
                }else{
                    if(null!=data){
                        //支付html源码信息
                        apiResponseData.setMessage(data);
                        l.success1(apiResponseData);
                    }else{
                        l.success0(apiResponseData);
                    }
                }
            }
        };
    }



    private static ApiResponseData setData(ApiResponseData apiResponseData,JSONObject   retInfo){
        JSONArray  update = retInfo.optJSONArray("update");
        JSONArray  delete = retInfo.optJSONArray("delete");
        if(null!=update){
            apiResponseData.setUpdateAry(update);
        }
        if(null!=delete){
            apiResponseData.setDeleteAry(delete);
        }
        return apiResponseData;
    }

    /**
     * 对象返回错误监听
     *
     * @param l
     *            回调
     * @return
     */
    protected  static <T> Response.ErrorListener responseErrorT(
            final ApiResponseJsonListener l,final Integer requestType) {
        return new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError e) {
                Log.e(TAG,".......onErrorResponse......."+e.toString());
                ApiResponseData apiResponseData = new ApiResponseData();
                apiResponseData.setRquestType(requestType);
                apiResponseData.setMessage(e.toString());
                l.error(apiResponseData);

            }
        };
    }

    /**
     * 成功消息监听 返回String
     *
     * @param l
     *            String 接口
     * @return
     */
    protected static  Response.Listener<byte[]> responseListener(
            final ApiResponseListener l) {
        return new Response.Listener<byte[]>() {
            @Override
            public void onResponse(byte[] arg0) {
                String data = null;
                try {
                    data = new String(arg0, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                l.requestSuccess(data);

            }
        };
    }

    /**
     * String 返回错误监听
     *
     * @param l
     *            String 接口
     * @return
     */
    protected  static Response.ErrorListener responseError(
            final ApiResponseListener l) {
        return new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError e) {
                l.requestError(e);

            }
        };
    }

    /**
     * add Request
     * @param request
     * @param context
     */
    public  static void addRequest(final Request<?> request, final Context context) {
	/*	if (context != null) {
			request.setTag(context);
		}*/
        mRequestQueue.add(request);
    }

    /**
     * 当主页面调用协议 在结束该页面调用此方法
     *
     * @param context
     */
    public static void cancelAll(final Context context) {
        mRequestQueue.cancelAll(context);
    }

    public  static void cancelAll( ) {
        mRequestQueue.cancelAll();
    }
    public static  void start( ) {
        mRequestQueue.start();
    }

    /**
     *  common params
     * @param params
     * @param context
     * @return
     */
    public  static ApiRequestParams commonParams(final Integer requestType,final ApiRequestParams params,final Context context){
        String   uuid= TDevice.getDeviceId(context);
        long     utcTime = TimeZoneUtil.getCurrentUTCTimeAsLong();
        String   sappver = TDevice.getVersionName();

        boolean  iszh  = TDevice.isZh(context);
        User user = UserDataCache.getInstance().getUserinfor();
        if(null!=user){
            params.put("userId",user.getUserId());
            params.put("token",user.getToken());
        }
        params.put("platform", ApiConstans.PLATFORM);
        params.put("os_ver",android.os.Build.VERSION.SDK_INT+"");
        params.put("app_ver",sappver);
        params.put("uuid",uuid);
        params.put("client_lang",iszh?"zh":"en");
        params.put("sig", TDevice.generateSig(String.valueOf(utcTime)));
        params.put("timestamp",String.valueOf(utcTime));       //每次客户端生成的时间戳
        //params.put("data_timestamp",data_timestamp);           //为上一次服务端返回给客户端的时间戳,第一次为0。用于服务于进行数据更新比对，返回更新的数据
        params.put("country_code", UserData.getInstance().getUserinfor().area);
        params.put("device_type", TDevice.isPad(context));
        Log.e(TAG,"params:"+params.getParamsList());
        return params;
    }

}
